//
//  MTPartyGiftSelectView.swift
//  MT
//
//  Created by ooops on 2020/5/25.
//  Copyright © 2020 张强. All rights reserved.
//

import Foundation
import MTCategory

protocol MTPartyGiftSelectViewDelegate: NSObjectProtocol {
    func didTapCustomGiftCount(count: Int)
    func giftSelectDidRemoveFromSuperView()
}

extension MTPartyGiftSelectView: UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate {
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        if let v = touch.view, v.isDescendant(of: self.collectionView) {
            return false
        }
        return true
    }
    
    public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: MTPartyGiftSelectCell = collectionView.dequeueReusableCell(withReuseIdentifier: MTPartyGiftSelectCell.reuseIdentity(), for: indexPath) as! MTPartyGiftSelectCell
        let data = self.dataSource[indexPath.item < dataSource.count ? indexPath.item : indexPath.item - 1]
        if indexPath.item == collectionView.numberOfItems(inSection: 0) - 1 {
            cell.bindData(data: data, isHiddenContent: true)
        } else {
            cell.bindData(data: data, isHiddenContent: false)
        }
        return cell
    }
    
    //MARK: UICollectionViewDelegate
    
    public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.item == collectionView.numberOfItems(inSection: 0)  - 1 {
            self.delegate?.didTapCustomGiftCount(count: 0)
            self.removeFromSuperview()
        } else {
            let data = self.dataSource[indexPath.item]
            self.delegate?.didTapCustomGiftCount(count: data.count)
            removeLayer(indexPath: indexPath)
//            self.removeFromSuperview()
        }
    }
    
    public func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        
    }
    
    
    private func removeLayer(indexPath: IndexPath) {
        
        for i in 0..<self.dataSource.count {
            //var model = self.dataSource[i]
            if indexPath.item == i {
                self.dataSource[i].isSelected = true
            } else {
                self.dataSource[i].isSelected = false
            }
            if i == dataSource.count {
                self.dataSource[i].isSelected = false
            }
        }
        
        self.collectionView.reloadData()
        
    }
}

class MTPartyGiftSelectView: UIView {
    
    private var selectedModel: PartyGiftItemStruct?
    var dataSource: [PartyGiftItemStruct] = [] {
        didSet {
            self.collectionView.reloadData()
        }
    }
    
    weak var delegate: MTPartyGiftSelectViewDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        makeConstraint()
//        let tap = UITapGestureRecognizer(target: self, action: #selector(MTPartyGiftSelectView.didTap(tap:)))
//        tap.delegate = self
//        self.addGestureRecognizer(tap)
        self.collectionView.reloadData()
    }
    
    //@objc private func didTap(tap: UITapGestureRecognizer) {
    @objc private func didTap() {
//        UIView.animate(withDuration: 0.25, animations: {
            
            self.frame = CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: 300)
            
//        }) { (flag) in
            self.removeFromSuperview()
//        }
        self.delegate?.giftSelectDidRemoveFromSuperView()
    }
    
    private func setupUI() {
        addSubview(bottomContentView)
        bottomContentView.addSubview(topLabel)
        bottomContentView.addSubview(closeButton)
        bottomContentView.addSubview(lineView)
        bottomContentView.addSubview(bottomTipLabel)
        bottomContentView.addSubview(commitButton)
        bottomContentView.addSubview(collectionView)
    }
    
    private func makeConstraint() {
//        bottomContentView.snp.makeConstraints { (make) in
//            make.left.right.bottom.equalToSuperview()
//            make.height.equalTo(300)
//        }
        topLabel.snp.makeConstraints { (make) in
            make.top.left.equalToSuperview().offset(10)
        }
        
        closeButton.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(10)
            make.size.equalTo(CGSize(width: 20, height: 20))
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(topLabel.snp.bottom).offset(10)
            make.height.equalTo(1)
        }
        
        bottomTipLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(10)
        }
        
        commitButton.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(bottomTipLabel.snp.bottom).offset(25)
            //make.bottom.equalToSuperview().offset(-ScreenBottomExtraOffset - 22)
            make.size.equalTo(CGSize(width: 332, height: 49))
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            let itemWidth = (ScreenWidth - 12.0 * 2 - 1 - 8 * 2) / 3
            let h = itemWidth * 80 / 112
            make.height.equalTo(h * 2 + 10 + 20)
            make.top.equalTo(lineView.snp.bottom)
        }
    }
    
    override func didMoveToWindow() {
        super.didMoveToWindow()
        self.backgroundColor = UIColor(hex: 0x000000, alpha: 0.5)
        UIView.animate(withDuration: 0.25) {
            let itemWidth = (ScreenWidth - 12.0 * 2 - 1 - 8 * 2) / 3
            let h = 344 * ScreenWidth / 375.0
            self.bottomContentView.frame = CGRect(x: 0, y: ScreenHeight - h, width: ScreenWidth, height: h)
        }
    }
    
    lazy var topLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(16)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "选择礼物数量"
        return l
    }()
    
    lazy var closeButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "close-black"), for: .normal)
        btn.addTarget(self, action: #selector(MTPartyGiftSelectView.close), for: .touchUpInside)
        return btn
    }()
    
    lazy var commitButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("确定", for: .normal)
        btn.addTarget(self, action: #selector(MTPartyGiftSelectView.commit), for: .touchUpInside)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.layer.cornerRadius = 24.5
        btn.layer.masksToBounds = true
        return btn
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor.seprateLine.x707070
        return v
    }()
    
    lazy var bottomTipLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCRegularFont(10)
        l.textColor = UIColor.text.x1d1a1a
        l.text = "聚会成功礼物才会发放，取消或未能成功举办，礼物会全额退款"
        return l
    }()
    
    @objc private func commit() {
        didTap()
    }
    
    @objc private func close() {
        didTap()
    }
    
    lazy var collectionView: UICollectionView = {
        /// 设置大小
        let inset: CGFloat = 12.0
        let itemWidth = (ScreenWidth - inset * 2 - 1 - 8 * 2) / 3
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth * 80 / 112)
        flowLayout.minimumLineSpacing = 8
        flowLayout.minimumInteritemSpacing = 8
        let cv = UICollectionView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: MiTuGiftView.collectionViewHeight), collectionViewLayout: flowLayout)
        cv.backgroundColor = UIColor.white
        cv.contentInset = UIEdgeInsets(top: inset, left: inset, bottom: inset, right: inset)
        cv.showsVerticalScrollIndicator = false
        cv.isScrollEnabled = false
        cv.delegate = self
        cv.dataSource = self
        //        cv.isPagingEnabled = true
        cv.showsHorizontalScrollIndicator = false
        /// 注册 Cell
        cv.register(MTPartyGiftSelectCell.self, forCellWithReuseIdentifier: MTPartyGiftSelectCell.reuseIdentity())
        return cv
    }()
    
    lazy var bottomContentView: UIView = {
        let v = UIView()
        v.backgroundColor = .white
        v.frame = CGRect(x: 0, y: ScreenHeight, width: ScreenWidth, height: 300)
        return v
    }()
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }


}
